<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * External groups API
 *
 * @package    moodlecore
 * @subpackage webservice
 * @copyright  2009 Moodle Pty Ltd (http://moodle.com)
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

require_once("$CFG->libdir/externallib.php");
//TODO sin acabar
class moodle_labis_external extends external_api {
   public static function labis_test_parameters(){
      return new external_function_parameters(
                array(
                   'test' =>new external_value(PARAM_INT, 'entrada de numero de testing'),
                ), 'es un elemento simple que es un entero' 
      );

   }


//   public static function labis_test_parameters(){
//      return new external_function_parameters(
//                array(
//                   'test' =>new external_value(PARAM_INT, 'entrada de numero de testing'),
//                ), 'es un elemento simple que es un entero' 
//      );
//
//   }


   //esto si que es para documentarlo....
   //vamos lo siguiente es porque por un lado me pide que tenga un nombre los metodos pero por otro llaman a otros nombres.
   //me imagino que el problema es haber metido la palabra labis por en medio.
   //hay que documentar esta mierda.
   public static function create_test_parameters(){
      return self::labis_test_parameters();
   }
   public static function labis_test_returns(){

        return new external_single_structure(
                  array(
                     'test' =>new external_value(PARAM_INT, 'salida de numero de testing'),
                  ), 'es un elemento simple que es un entero.'
        );

   }


   public static function labis_test($numero){
      global $CFG, $DB;
      $params = self::validate_parameters(self::create_test_parameters(), array('test' => $numero));
      $transaction = $DB->start_delegated_transaction();

      //aqui hay que hacer cosas

      $transaction->allow_commit();
      return array('test' => $numero);

   }





   //aplicacion externa para obtencion de cursos
   public static function labis_cursos_parameters(){
      return new external_function_parameters(array(), 'no se reciben parametros');
   }


   public static function labis_cursos_returns(){

         return new external_multiple_structure(
                new external_single_structure(
                        array(
                            'id' => new external_value(PARAM_INT, 'course id'),
                            'fullname' => new external_value(PARAM_TEXT, 'full name'),
                        ), 'course'
                )
        );

   }


   public static function labis_cursos(){
      global $CFG, $DB;
      require_once($CFG->dirroot."/webservice/lib.php");

      $params = self::validate_parameters(self::labis_cursos_parameters(), array());
      $transaction = $DB->start_delegated_transaction();

      //TODO aqui hay que hacer cosas

      $cursosobj = enrol_get_my_courses(array('id', 'fullname'),'visible DESC,sortorder ASC', 0);

      $transaction->allow_commit();
      $cursos=array();
      foreach ($cursosobj as $cursoobj) {
         if ($cursoobj->id == SITEID) {
            continue;
         }

         $cursos[]=array('id'=>$cursoobj->id,'fullname'=>$cursoobj->fullname);
      }
     
      return $cursos;

   }






   //aplicacion externa para obtencion de actividades
   public static function labis_actividades_parameters(){
      return new external_function_parameters(
                array(
                   'curso' =>new external_value(PARAM_INT, 'id del curso'),
                ), 'se pasa el id del curso'
      );

   }

   public static function labis_actividades_returns(){

         return new external_multiple_structure(
                new external_single_structure(
                        array(
                            'id' => new external_value(PARAM_INT, 'id de la actividad'),
                            'fullname' => new external_value(PARAM_TEXT, 'nombre de la actividad'),
                        ), 'actividad'
                )
        );

   }


   public static function labis_actividades($curso){
      global $CFG, $DB;
      require_once($CFG->dirroot."/webservice/lib.php");
      require_once($CFG->dirroot."/course/lib.php");

      $params = self::validate_parameters(self::labis_actividades_parameters(), array('curso' => $curso));
      $transaction = $DB->start_delegated_transaction();

      //TODO aqui hay que hacer cosas
      $actividadesobj = get_array_of_activities($curso);

      $transaction->allow_commit();

      $actividades=array();
      foreach ($actividadesobj as $actividadobj) {
         if($actividadobj->mod == 'assignment')
            $actividades[]=array('id'=>$actividadobj->cm,'fullname'=>$actividadobj->name);
      }
     
      return $actividades;
   }




   //aplicacion externa para obtencion de participantes
   public static function labis_participantes_parameters(){
      return new external_function_parameters(
                array(
                   'actividad' =>new external_value(PARAM_INT, 'id de la actividad'),
                ), 'se pasa el id de la actividad'
      );

   }

   public static function labis_participantes_returns(){

         return new external_multiple_structure(
                new external_single_structure(
                        array(
                            'id' => new external_value(PARAM_INT, 'id del participante'),
                            'fullname' => new external_value(PARAM_TEXT, 'nombre del participante'),
                        ), 'participante'
                )
        );

   }


   public static function labis_participantes($actividad){
      global $CFG, $DB;
      require_once($CFG->dirroot."/webservice/lib.php");
      require_once($CFG->dirroot."/mod/assignment/lib.php");
      require_once($CFG->dirroot."/lib/moodlelib.php");
      require_once($CFG->dirroot."/user/lib.php");

      $params = self::validate_parameters(self::labis_participantes_parameters(), array('actividad' => $actividad));

      $transaction = $DB->start_delegated_transaction();

      //TODO aqui hay que hacer cosas
      //$participantesobj = assignment_get_participants($actividad);
 
      //$caca = assignment_get_user_grades($actividad);





if ($actividad) {
    if (! $cm = get_coursemodule_from_id('assignment', $actividad)) {
        print_error('invalidcoursemodule');
    }

    if (! $assignment = $DB->get_record("assignment", array("id"=>$cm->instance))) {
        print_error('invalidid', 'assignment');
    }

    if (! $course = $DB->get_record("course", array("id"=>$assignment->course))) {
        print_error('coursemisconf', 'assignment');
    }

} else {
    if (!$assignment = $DB->get_record("assignment", array("id"=>$a))) {
        print_error('invalidcoursemodule');
    }
    if (! $course = $DB->get_record("course", array("id"=>$assignment->course))) {
        print_error('coursemisconf', 'assignment');
    }
    if (! $cm = get_coursemodule_from_instance("assignment", $assignment->id, $course->id)) {
        print_error('invalidcoursemodule');
    }
  }
   require_login($course->id, false, $cm);

   require_capability('mod/assignment:grade', get_context_instance(CONTEXT_MODULE, $cm->id));

/// Load up the required assignment code
   require($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
   $assignmentclass = 'assignment_'.$assignment->assignmenttype;
   $actividadobj = new $assignmentclass($cm->id, $assignment, $cm, $course);

   $context = get_context_instance(CONTEXT_MODULE, $cm->id);
   $currentgroup = groups_get_activity_group($cm, true);
   list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $currentgroup);

   $sql = "SELECT u.id FROM {user} u ".
          "LEFT JOIN ($esql) eu ON eu.id=u.id ".
          "WHERE u.deleted = 0 AND eu.id=u.id ";
   $users = $DB->get_records_sql($sql, $params);

      $transaction->allow_commit();

   if (!empty($users)) {
      $users = array_keys($users);
   }


       $participantes=array();
       foreach ($users as $id) {
          $idarray = array();
          $idarray[] = $id;
          $fullname = user_get_users_by_id($idarray);
          $fullname = fullname($fullname[$id]);
          $participantes[]=array('id'=>$id,'fullname'=>$fullname);
       }

         






     //throw new Exception(print_r ($users));
      //throw new Exception(print_r ($participantes));
      return $participantes;
    }




   //aplicacion externa para escritura de grades
   public static function labis_set_grades_parameters(){
      return new external_function_parameters(
                array(
                   'actividad' =>new external_value(PARAM_INT, 'id de la actividad'),
                   'usuario' =>new external_value(PARAM_INT, 'id de la actividad'),
                   'nota' =>new external_value(PARAM_INT, 'id de la actividad'),
                ), 'se pasa el id de la actividad y id de usuario y nota'
      );

   }


   public static function labis_set_grades_returns(){

 return new external_single_structure(
                  array(
                     'ok' =>new external_value(PARAM_INT, '1 significa ok'),
                  ), '1 significa ok.'
        );
   }


   public static function labis_set_grades($actividad,$usuario,$nota){
      global $CFG, $DB, $USER;
      require_once($CFG->libdir.'/gradelib.php');
      
      $params = self::validate_parameters(self::labis_set_grades_parameters(), array('actividad' => $actividad,
                                                                                     'usuario' => $usuario,
                                                                                     'nota' => $nota, ));
      $transaction = $DB->start_delegated_transaction();

      //aqui hay que hacer cosas



if ($actividad) {
    if (! $cm = get_coursemodule_from_id('assignment', $actividad)) {
        print_error('invalidcoursemodule');
    }

    if (! $assignment = $DB->get_record("assignment", array("id"=>$cm->instance))) {
        print_error('invalidid', 'assignment');
    }

    if (! $course = $DB->get_record("course", array("id"=>$assignment->course))) {
        print_error('coursemisconf', 'assignment');
    }

} else {
    if (!$assignment = $DB->get_record("assignment", array("id"=>$a))) {
        print_error('invalidcoursemodule');
    }
    if (! $course = $DB->get_record("course", array("id"=>$assignment->course))) {
        print_error('coursemisconf', 'assignment');
    }
    if (! $cm = get_coursemodule_from_instance("assignment", $assignment->id, $course->id)) {
        print_error('invalidcoursemodule');
    }
  }
   require_login($course->id, false, $cm);

   require_capability('mod/assignment:grade', get_context_instance(CONTEXT_MODULE, $cm->id));

/// Load up the required assignment code
   require($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
   $assignmentclass = 'assignment_'.$assignment->assignmenttype;
   $actividadobj = new $assignmentclass($cm->id, $assignment, $cm, $course);


   $grading_info = grade_get_grades($actividadobj->course->id, 'mod', 'assignment', $actividadobj->assignment->id, $usuario);

        // store outcomes if needed
        $actividadobj->process_outcomes($usuario);

        $submission = $actividadobj->get_submission($usuario, true);  // Get or make one

        if (!($grading_info->items[0]->grades[$usuario]->locked ||
            $grading_info->items[0]->grades[$usuario]->overridden) ) {

            $submission->grade      = $nota;
            $submission->submissioncomment    = 'nota editada desde un dispositivo movil';
            $submission->teacher    = $USER->id;
            $mailinfo = get_user_preferences('assignment_mailinfo', 0);
            if (!$mailinfo) {
                $submission->mailed = 1;       // treat as already mailed
            } else {
                $submission->mailed = 0;       // Make sure mail goes out (again, even)
            }
            $submission->timemarked = time();

            unset($submission->data1);  // Don't need to update this.
            unset($submission->data2);  // Don't need to update this.

            if (empty($submission->timemodified)) {   // eg for offline assignments
                // $submission->timemodified = time();
            }

            $DB->update_record('assignment_submissions', $submission);

            // triger grade event
            $actividadobj->update_grade($submission);
      //throw new Exception(print_r ($submission));
      $transaction->allow_commit();

      return array('ok' => 1);

   }
}

}


